package com.cms.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.util.Base64;

import com.alibaba.fastjson.JSONObject;
import com.cms.Config;
import com.cms.Feedback;
import com.cms.entity.Admin;
import com.cms.entity.Member;
import com.cms.util.DeviceUtils;
import com.cms.util.SystemUtils;
import com.cms.util.WeixinUtils;

public class PermissionFilter implements Filter{
    
    /** 不包含 */
    private List<String> adminExcludes = new ArrayList<String>(){{
        add("/admin/login");
        add("/admin/error");
        add("/admin/static");
    }};
    
    /** 不包含 */
    private List<String> permissionExcludes = new ArrayList<String>(){{
        add("/admin/logout");
        add("/admin/common");
        add("/admin/file");
        add("/admin/resource");
        add("/admin/profile");
    }};
    
    /** 不包含 */
    private List<String> memberExcludes = new ArrayList<String>(){{
        add("/register");
        add("/login");
        add("/password");
        add("/payment/alipayNotify");
        add("/payment/weixinNotify");
    }};
    
    /** 包含 */
    private List<String> memberIncludes = new ArrayList<String>(){{
        add("/member");
        add("/member/");
        add("/order/");
        add("/receiver/");
        add("/payment/");
        add("/cart/list");
    }};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        // TODO Auto-generated method stub
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String url = request.getRequestURI().toString();
        String contextPath = request.getContextPath();
        url = url.substring(contextPath.length());
        if(StringUtils.isBlank(url) 
                || url.startsWith("/upload") 
                || url.startsWith("/static") 
                || url.startsWith("/common")
                || StringUtils.isNotBlank(FilenameUtils.getExtension(url))
            ){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
//        //微信登录
//        if(DeviceUtils.isWechat(request)){
//        	 Member currentMember = (Member) request.getSession().getAttribute(Member.SESSION_MEMBER);
//         	if(currentMember!=null || url.startsWith("/login")){
//     	        filterChain.doFilter(servletRequest, servletResponse);
//                 return;
//         	}
//         	Config config = SystemUtils.getConfig();
//         	String queryString = request.getQueryString();
//         	String newUrl = url;
//         	Map<String,String> map = new HashMap<>();
//         	map.put("newUrl", newUrl);
//         	if(StringUtils.isNotBlank(queryString)){
//         		map.put("queryString", queryString);
//         	}
//         	String mapJson = JSONObject.toJSONString(map);
//         	String state = Base64.encodeBase64String(mapJson.getBytes("UTF-8"));
//        	//公众号
//        	response.sendRedirect(WeixinUtils.getAuthorizeUrl(URLEncoder.encode(config.getSiteUrl()+"/login/weixinReturn", "UTF-8"), state));
//        	return;
//        }
        //匹配member
        for(String key : memberExcludes){
            if(url.startsWith(key)){
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }
        for(String key : memberIncludes){
            if(url.startsWith(key)){
                Member currentMember = (Member) request.getSession().getAttribute(Member.SESSION_MEMBER);
            	if(currentMember!=null){
        	        filterChain.doFilter(servletRequest, servletResponse);
                    return;
            	}
        		response.sendRedirect(contextPath+"/login");
        		return;
               
            }
        }
        if(!url.startsWith("/admin")){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //匹配admin
        for(String key : adminExcludes){
            if(url.startsWith(key)){
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }
        Admin currentAdmin = (Admin) request.getSession().getAttribute(Admin.SESSION_ADMIN);
        if(currentAdmin!=null){
            for(String key : permissionExcludes){
                if(url.startsWith(key)){
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }
            }
            List<String> permissions = currentAdmin.getPermissions();
            for(String key : permissions){
                if(url.startsWith(key)){
                	//演示程序不允许修改、新增、删除开始《购买者需要删除》
                	if("read".equals(currentAdmin.getUsername())){
                		String lowerUrl = url.toLowerCase();
                		if(lowerUrl.contains("save") 
                				|| lowerUrl.contains("update") 
                				|| lowerUrl.contains("delete")
                				|| lowerUrl.contains("backup")
                				|| lowerUrl.contains("restore")
                				){
                			if("XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"))){
                				//是ajax操作
                				response.setContentType("application/json;charset=UTF-8");  
                				PrintWriter writer = response.getWriter();  
                				writer.write(JSONObject.toJSONString(Feedback.error("演示账号不允许操作!")));
                				writer.flush();
                				writer.close();  
                				return;
                			}else{
                				//是url操作
                				response.setContentType("text/html;charset=utf-8");  
                				PrintWriter writer = response.getWriter();  
                				writer.write("<script>alert('演示账号不允许操作!');history.back();</script>");
                				writer.flush();
                				writer.close(); 
                				return;
                			}
                		}
                	}
                	//演示程序不允许修改、新增、删除结束《购买者需要删除》
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }
            }
            response.sendRedirect(contextPath+"/admin/error/unauthorized");
            return;
        }
        response.sendRedirect(contextPath+"/admin/login");
        return;
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        
    }

}
